package com.cfuture08.eweb4j.mvc;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cfuture08.eweb4j.cache.MVCConfigBeanCache;
import com.cfuture08.eweb4j.cache.SingleBeanCache;
import com.cfuture08.eweb4j.config.ConfigConstant;
import com.cfuture08.eweb4j.config.EWeb4JConfig;
import com.cfuture08.eweb4j.config.bean.ConfigBean;
import com.cfuture08.eweb4j.config.log.LogFactory;
import com.cfuture08.eweb4j.mvc.config.bean.MVCConfigBean;
import com.cfuture08.util.LogUtil;

public class EWeb4JFilter implements Filter {
	public void init(FilterConfig arg0) throws ServletException {
		String mess = "---eweb4j starting";
		System.out.println(mess);
		LogUtil.getLogger().info(mess);
		LogFactory.getMVCLogger().write(mess);
	}

	public void destroy() {
		String mess = "---eweb4j close";
		System.out.println(mess);
		LogUtil.getLogger().info(mess);
		LogFactory.getMVCLogger().write(mess);
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) {
		PrintWriter out = null;
		String message = EWeb4JConfig.start();
		try {
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");

			if (message == null) {
				ConfigBean cb = (ConfigBean) SingleBeanCache
						.get(ConfigConstant.CONFIGBEAN_ID);
				String debug = (cb == null ? "1" : cb.getMvc().getDebug());
				HttpServletRequest req = (HttpServletRequest) request;
				HttpServletResponse res = (HttpServletResponse) response;
				req.setCharacterEncoding("utf-8");
				res.setCharacterEncoding("utf-8");
				res.setContentType("text/html");
				String uri = req.getRequestURI();
				String name = uri.replace(req.getContextPath() + "/", "");
				Map<String, String> error = null;
				if (MVCConfigBeanCache.containsKey(name)) {
					out = response.getWriter();
					// ------log-------
					StringBuilder sb = new StringBuilder();
					sb.append("MVC:从缓存中找到").append(name).append("[Action];");
					if ("true".equals(debug) || "1".equals(debug)) {
						System.out.println(sb.toString());
					}
					LogFactory.getMVCLogger().write(sb.toString());
					// ------log-------
					MVCConfigBean mvcBean = MVCConfigBeanCache.get(name);
					Map<String, String[]> map = req.getParameterMap();
					error = DoValidate.checkValidate(mvcBean, map, req);
					if (error != null) {
						sb = null;
						sb = new StringBuilder();
						sb.append("MVC:验证器发现了错误").append(error);
						if ("true".equals(debug) || "1".equals(debug)) {
							System.out.println(sb.toString());
						}
						LogFactory.getMVCLogger().write(sb.toString());
						DoValidate.doValidate(mvcBean, error, req, res, out);
						return;
					} else {
						sb = null;
						sb = new StringBuilder();
						sb.append("MVC:执行").append(name).append("[Action];");
						if ("true".equals(debug) || "1".equals(debug)) {
							System.out.println(sb.toString());
						}
						LogFactory.getMVCLogger().write(sb.toString());
						if (DoAction.checkAndDoAction(mvcBean, map, req, res,
								out) != null) {
							return;
						} else {

						}
					}
				}
				StringBuilder sb = new StringBuilder();
				sb.append("MVC:没有Action被执行，正常访问url:").append(uri);
				if ("true".equals(debug) || "1".equals(debug)) {
					System.out.println(sb.toString());
				}
				LogFactory.getMVCLogger().write(sb.toString());

				chain.doFilter(request, response);
			} else {
				out = response.getWriter();
				out.print(HtmlCreator.create(message));
				out.flush();
				out.close();
				String error = new StringBuilder("错误：").append(message)
						.toString();
				LogUtil.getLogger().error(error);
				LogFactory.getMVCLogger().write(error);
				return;
			}
		} catch (Exception e) {
			LogUtil.getLogger().error("", e);
			LogFactory.getMVCLogger().write(e.getMessage());
			e.printStackTrace();
			return;
		}
	}
}
